<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ShuGoAI</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
  <style>
    .app-layout {
      display: flex;
      height: 100vh;
    }

    .sidebar {
      width: 200px;
      background-color: #f4f4f9;
      padding: 20px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .logo-section {
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .logo-text {
      font-size: 18px;
      font-weight: bold;
      margin-top: 10px;
    }

    .new-chat-button {
      width: 100%;
      margin-top: 20px;
      padding: 10px;
      border: none;
      background-color: #409EFF;
      color: white;
      cursor: pointer;
      border-radius: 4px;
    }

    .new-chat-button:hover {
      background-color: #66b1ff;
    }

    .main-content {
      flex: 1;
      padding: 20px;
      overflow-y: auto;
    }

    .chat-container {
      display: flex;
      flex-direction: column;
      height: 100%;
    }

    .message-list {
      flex: 1;
      overflow-y: auto;
      padding: 10px;
      border: 1px solid #e0e0e0;
      border-radius: 4px;
      background-color: #fff;
      margin-bottom: 10px;
      display: flex;
      flex-direction: column;
    }

    .message {
      margin-bottom: 10px;
      padding: 10px;
      border-radius: 4px;
      display: flex;
    }

    .user-message {
      max-width: 70%;
      background-color: #e1f5fe;
      align-self: flex-end;
      flex-direction: row-reverse;
    }

    .bot-message {
      max-width: 100%;
      background-color: #f1f8e9;
      align-self: flex-start;
    }

    .message-icon {
      margin: 0 10px;
      font-size: 1.2em;
    }

    .loading-dots {
      padding-left: 5px;
    }

    .dot {
      display: inline-block;
      margin-left: 5px;
      width: 8px;
      height: 8px;
      background-color: #000000;
      border-radius: 50%;
      animation: pulse 1.2s infinite ease-in-out both;
    }

    .dot:nth-child(2) {
      animation-delay: -0.6s;
    }

    @keyframes pulse {

      0%,
      100% {
        transform: scale(0.6);
        opacity: 0.4;
      }

      50% {
        transform: scale(1);
        opacity: 1;
      }
    }

    .input-container {
      display: flex;
    }

    .input-container input {
      flex: 1;
      margin-right: 10px;
      padding: 10px;
      border: 1px solid #dcdcdc;
      border-radius: 4px;
    }

    .input-container button {
      padding: 10px 20px;
      border: none;
      background-color: #409EFF;
      color: white;
      cursor: pointer;
      border-radius: 4px;
    }

    .input-container button:disabled {
      background-color: #a0cfff;
    }

    @media (max-width: 768px) {
      .main-content {
        padding: 10px 0 10px 0;
      }

      .app-layout {
        flex-direction: column;
      }

      .sidebar {
        width: 100%;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        padding: 10px;
      }

      .logo-section {
        flex-direction: row;
        align-items: center;
      }

      .logo-text {
        font-size: 20px;
      }

      .logo-section img {
        width: 40px;
        height: 40px;
      }

      .new-chat-button {
        margin-right: 30px;
        width: auto;
        margin-top: 5px;
      }
    }

    @media (min-width: 769px) {
      .main-content {
        padding: 0 0 10px 10px;
      }

      .app-layout {
        display: flex;
        height: 100vh;
      }

      .sidebar {
        width: 200px;
        background-color: #f4f4f9;
        padding: 20px;
        display: flex;
        flex-direction: column;
        align-items: center;
      }

      .logo-section {
        display: flex;
        flex-direction: column;
        align-items: center;
      }

      .logo-text {
        font-size: 18px;
        font-weight: bold;
        margin-top: 10px;
      }

      .new-chat-button {
        width: 100%;
        margin-top: 20px;
      }
    }

    /* 新增样式  换行问题 */
    .bot-message span, .user-message span {
      white-space: pre-line;
      display: inline-block;
    }
  </style>
</head>

<body>
<div class="app-layout">
  <div class="sidebar">
    <div class="logo-section">
      <img src="./images/logo.png" alt="沭河谷大健康人工智能助手" width="160" height="160" />
      <span class="logo-text">ShuGoAi</span>
    </div>
    <button class="new-chat-button" onclick="newChat()">
      <i class="fa-solid fa-plus"></i>
      &nbsp;新会话
    </button>
  </div>
  <div class="main-content">
    <div class="chat-container">
      <div class="message-list" id="message-list">
        <!-- 示例消息 -->
      </div>
      <div class="input-container">
        <input type="text" id="input-message" placeholder="请输入消息" />
        <button type="button" onclick="sendMessage()">发送</button>
      </div>
    </div>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  let isSending = false;
  let uuid = localStorage.getItem('user_uuid') || uuidToNumber(uuidv4());
  localStorage.setItem('user_uuid', uuid);
  let messages = [];

  $(document).ready(function () {
    hello();
    $('#input-message').keypress(function (e) {
      if (e.which === 13) {
        sendMessage();
      }
    });
  });

  function scrollToBottom() {
    $('#message-list').scrollTop($('#message-list')[0].scrollHeight);
  }

  function hello() {
    sendRequest('你好');
  }

  function sendMessage() {
    const message = $('#input-message').val().trim();
    if (message) {
      sendRequest(message);
      $('#input-message').val('');
    }
  }

  function sendRequest(message) {
    if (isSending) return;
    isSending = true;

    const userMsg = {
      isUser: true,
      content: message,
      isTyping: false,
      isThinking: false
    };

    if (messages.length > 0) {
      messages.push(userMsg);
      appendMessage(userMsg);
    }

    const botMsg = {
      isUser: false,
      content: '',
      isTyping: true,
      isThinking: false
    };

    messages.push(botMsg);
    appendMessage(botMsg);
    scrollToBottom();

    $.ajax({
      url: 'http://localhost:8000/ShuGo/chat',
      method: 'POST',
      data: JSON.stringify({
        memoryId: uuid,
        message
      }),
      contentType: 'application/json',
      xhrFields: {
        onprogress: function (e) {
          const fullText = e.currentTarget.responseText;
          let newText = fullText.substring(botMsg.content.length);
          botMsg.content += newText;
          updateMessage(botMsg);
          scrollToBottom();
        }
      },
      success: function () {
        botMsg.isTyping = false;
        isSending = false;
        updateMessage(botMsg);
      },
      error: function (error) {
        console.error('流式错误:', error);
        botMsg.content = '请求失败，请重试';
        botMsg.isTyping = false;
        isSending = false;
        updateMessage(botMsg);
      }
    });
  }

  function appendMessage(message) {
    const messageElement = $('<div>').addClass('message').addClass(message.isUser ? 'user-message' : 'bot-message');
    const iconClass = message.isUser ? 'fa-solid fa-user' : 'fa-solid fa-robot';
    messageElement.append($('<i>').addClass(iconClass).addClass('message-icon'));
    const contentSpan = $('<span>').html(convertStreamOutput(message.content));
    if (message.isTyping) {
      contentSpan.append($('<span>').addClass('loading-dots').append($('<span>').addClass('dot')).append($('<span>')
              .addClass('dot')));
    }
    messageElement.append(contentSpan);
    $('#message-list').append(messageElement);
  }

  function updateMessage(message) {
    const messageElement = $('#message-list').children().eq(messages.indexOf(message));
    messageElement.empty();
    const iconClass = message.isUser ? 'fa-solid fa-user' : 'fa-solid fa-robot';
    messageElement.append($('<i>').addClass(iconClass).addClass('message-icon'));
    const contentSpan = $('<span>').html(convertStreamOutput(message.content));
    if (message.isTyping) {
      contentSpan.append($('<span>').addClass('loading-dots').append($('<span>').addClass('dot')).append($('<span>')
              .addClass('dot')));
    }
    messageElement.append(contentSpan);
  }

  function uuidv4() {
    return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
            (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
    );
  }

  function uuidToNumber(uuid) {
    let number = 0;
    for (let i = 0; i < uuid.length && i < 6; i++) {
      const hexValue = uuid[i];
      number = number * 16 + (parseInt(hexValue, 16) || 0);
    }
    return number % 1000000;
  }

  // function convertStreamOutput(output) {
  //   return output
  //           .replace(/\n/g, '<br>')
  //           .replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;')
  //           .replace(/&/g, '&amp;')
  //           .replace(/</g, '&lt;')
  //           .replace(/>/g, '&gt;');
  // }

  function convertStreamOutput(output) {
    return output
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/\t/g, '    '); // 保留原始换行符\n
  }


  function newChat() {
    console.log('开始新会话');
    localStorage.removeItem('user_uuid');
    location.reload();
  }
</script>
</body>

</html>
